var express = require('express');
var router = express.Router();

const moment = require('moment');
const AccountModule = require('../../models/AccountModel');

const checkTokenMiddleware = require('../../middlewares/checkTokenMiddleware');

/* GET home page. */
router.get('/account', checkTokenMiddleware, function(req, res, next) {
  // 获取到了用户id 可以通过用户id查询笔记，之前添加笔记时要新增用户id记录，这样就可以通过id查找笔记
  console.log(req.user);
    AccountModule.find()
    .sort({time: -1})
    .then(data => {
      res.json({
        code: '0000',
        msg: '读取成功',
        data
      })
    }).catch(err => {
      res.json({
        code:'1001',
        msg: '读取失败',
        data: null
      });
    });
  
});

//提交表单
router.post('/account', checkTokenMiddleware, function(req, res, next) {
  //表单验证
  let errCreatecode 
  if (typeof(req.body.title) !== 'string'){
    errCreatecode = '1002';
  }else if(typeof(req.body.type) !== 'number'){
    errCreatecode = '1004';
  }else if(typeof(req.body.account) !== 'number'){
    errCreatecode = '1005';
  }
  //插入数据库
  AccountModule.create({
    ...req.body,
    time: moment(new Date(req.body.time))
  }).then(data => {
    res.json({
      code: '0000',
      smg: '创建成功',
      data
    })
  }).catch(err => {
    res.json({
      code: errCreatecode,
      msg: '创建失败',
      data: null
    })
  });
  
});
//删除表单
router.delete('/account/:id', checkTokenMiddleware, function(req, res, next) {
  let id = req.params.id;

  AccountModule.deleteOne({_id: id})
  .then(data => {
    res.json({
      code:'0000',
      msg: '删除成功',
      data: {}
    })
  }).catch(err => {
      res.json({
        code:'1010',
        msg: '删除成功',
        data: null
      })
  });

  
});
//查询单条
router.get('/account/:id', checkTokenMiddleware, function(req, res, next) {
  let id = req.params.id;

  AccountModule.findById(id)
  .then(data => {
    res.json({
      code:'0000',
      msg: '查询成功',
      data: data
    })
  }).catch(err => {
      res.json({
        code:'1011',
        msg: '查询失败',
        data: null
      })
  });
  
});
//更新账单
router.patch('/account/:id', checkTokenMiddleware, function(req, res, next) {
  let id = req.params.id;

  AccountModule.updateOne({_id: id}, req.body)
  .then(data => {
    return AccountModule.findById(id);
  }).then(data => {
    res.json({
      code:'0000',
      msg: '更新成功',
      data: data
    })
  }).catch(err => {
    res.json({
      code:'1012',
      msg: '更新失败',
      data: null
    })
  });
  
});

module.exports = router;
